package com.ebt.m.activity;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.data.bean.FeedbackQuestion;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.rxModel.RxDataRequest;
import com.ebt.m.update.UpdateService;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.InputCheckUtil;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.widget.EBTProgress;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashSet;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by andy.wang on 2016/10/17.
 */

public class FeedbackActivity extends BaseToolBarActivity implements CompoundButton.OnCheckedChangeListener {

    @BindView(R.id.et_description)
    EditText etDescription;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.action_submit)
    Button actionSubmit;
    @BindView(R.id.progress_bar)
    EBTProgress progressBar;
    @BindView(R.id.success_container)
    LinearLayout successContainer;
    @BindView(R.id.content)
    ScrollView content;
    @BindView(R.id.type_progress)
    ProgressBar typeProgress;
    @BindView(R.id.load_type_fail)
    TextView loadTypeFail;
    @BindView(R.id.desc)
    TextView desc;
    @BindView(R.id.table_layout)
    TableLayout tableLayout;
    private HashSet<Integer> mSelectedTypes;
    private int mCountsPerRow = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
        setTitle("意见反馈");
        View view = View.inflate(this, R.layout.layout_4feedback, null);
        setContentView(view);
        ButterKnife.bind(this, view);
        desc.setText("感谢您对" + getResources().getString(R.string.app_name) + "的关注与支持，我们会认真处理您的反馈意见，尽快修复和完善相关功能！");
        mSelectedTypes = new HashSet<>();
        progressBar.setVisibility(View.GONE);
        successContainer.setVisibility(View.GONE);
        loadTypes();
    }

    private void loadTypes() {
        tableLayout.setVisibility(View.GONE);
        loadTypeFail.setVisibility(View.GONE);
        typeProgress.setVisibility(View.VISIBLE);
        AppInitService.getUrlApi().gotoFeedbackTypes(ConfigData.FEEDBACK_TYPES_URL, RxDataRequest.getRestHeader(RxDataRequest.FEEDBACK_TYPES))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(questions -> {
                    if (questions != null && questions.size() > 0) {
                        typeProgress.setVisibility(View.GONE);
                        loadTypeFail.setVisibility(View.GONE);
                        tableLayout.setVisibility(View.VISIBLE);
                        generateTypesTabLayout(questions);
                    } else {
                        typeProgress.setVisibility(View.GONE);
                        loadTypeFail.setVisibility(View.VISIBLE);
                        tableLayout.setVisibility(View.GONE);
                    }
                }, throwable -> {
                    typeProgress.setVisibility(View.GONE);
                    loadTypeFail.setVisibility(View.VISIBLE);
                    tableLayout.setVisibility(View.GONE);
                    NetUtils.checkHttpException(this, throwable);
                    Logger.e(throwable.getMessage());
                });
    }

    /**
     * 创建意见反馈类别
     * @param questions
     */
    private void generateTypesTabLayout(List<FeedbackQuestion> questions) {
        tableLayout.removeAllViews();
        int rows = questions.size() / mCountsPerRow + (questions.size() % mCountsPerRow > 0 ? 1 : 0);
        TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 10, 0, 10);
        for (int i = 0; i < rows; i++) {
            TableRow tableRow = new TableRow(this);
            tableRow.setOrientation(LinearLayout.HORIZONTAL);
            tableLayout.addView(tableRow, layoutParams);
        }
        TableRow.LayoutParams layoutParams1 = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams1.weight = 1;
        layoutParams1.width = 0;
        for (int y = 0; y < questions.size(); y++) {
            TableRow tableRow = (TableRow) tableLayout.getChildAt(y / mCountsPerRow);
            ToggleButton toggleButton = (ToggleButton) View.inflate(this, R.layout.layout_4feedback_type, null);
            toggleButton.setText(questions.get(y).getValue());
            toggleButton.setTextOn(questions.get(y).getValue());
            toggleButton.setTextOff(questions.get(y).getValue());
            toggleButton.setTag(questions.get(y).getId().getKey());
            toggleButton.setOnCheckedChangeListener(this);
            tableRow.addView(toggleButton, layoutParams1);
        }
    }

    @OnClick({R.id.action_submit, R.id.load_type_fail})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_submit:
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_SUBMIT_FEEDBACK);
                String description = etDescription.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                if (mSelectedTypes.size() < 1) {
                    Toast.makeText(this, "请选择问题类型", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(description)) {
                    Toast.makeText(this, "请填写问题描述", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(phone)) {
                    Toast.makeText(this, "请填写联系方式", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!InputCheckUtil.phoneCheck(phone)) {
                    Toast.makeText(this, "手机格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                progressBar.setVisibility(View.VISIBLE);
                AppInitService.getUrlApi().gotoFeedback(ConfigData.FEEDBACK_URL, RxDataRequest.getRestHeader(RxDataRequest.POST_TO_FEEDBACK), generateParams(description, phone))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(responseBodyResponse -> {
                            try {
                                String response = responseBodyResponse.body().string();
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getInt("result") == 1) {
                                    progressBar.setVisibility(View.GONE);
                                    content.setVisibility(View.GONE);
                                    successContainer.setVisibility(View.VISIBLE);
                                } else {
                                    progressBar.setVisibility(View.GONE);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(this, "提交失败", Toast.LENGTH_SHORT).show();
                            }
                        }, throwable -> {
                            progressBar.setVisibility(View.GONE);
                            NetUtils.checkHttpException(this, throwable);
                            Logger.e(throwable.getMessage());
                        });
                break;
            case R.id.load_type_fail:
                loadTypes();
                break;
        }
    }

    private String generateParams(String description, String phone) {
        try {
            UserInfo userLicenceInfo = AppContext.getCurrentUser();
            JSONObject paramObj = new JSONObject();
            paramObj.put("sysCode", "Question");
            JSONArray jsonArray = new JSONArray(mSelectedTypes);
            paramObj.put("questionType", jsonArray);
            paramObj.put("description", description);
            paramObj.put("connectTel", phone);
            paramObj.put("agentId", userLicenceInfo.getUserId());
            paramObj.put("agentName", userLicenceInfo.getUserName());
            JSONObject deviceObj = new JSONObject();
            deviceObj.put("opreateSys", Build.VERSION.RELEASE);
            deviceObj.put("device", Build.MODEL);
            paramObj.put("deviceInfo", deviceObj);
            JSONObject appInfoObj = new JSONObject();
            appInfoObj.put("app", "ZYJ-Android");
            appInfoObj.put("appVesion", UpdateService.getApkVersionName());
            paramObj.put("appInfo", appInfoObj);
            Logger.json(paramObj.toString());
            return paramObj.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        Integer selectedType = Integer.valueOf((String) compoundButton.getTag());
        if (b) {
            mSelectedTypes.add(selectedType);
        } else {
            mSelectedTypes.remove(selectedType);
        }
    }
}
